package com.yvon.maple.gateway.component;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.yvon.boot.redis.service.RedisService;
import com.yvon.maple.constants.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Set;

import static com.yvon.maple.constants.RedisKey.System.BACKEND_RESOURCE;
import static com.yvon.maple.constants.SystemConstant.Common.TOKEN_HEADER;

/**
 * 默认的授权管理器
 *
 * @author : Yvon
 * @since : 2021-11-30
 */
@Component
@Slf4j
public class DefaultAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();

        String restPath = request.getMethodValue() + "_" + request.getURI().getPath();
        log.info("请求路径：{}", restPath);

        List<String> token = request.getHeaders().get(TOKEN_HEADER);
        if (CollUtil.isEmpty(token)) {
            return Mono.just(new AuthorizationDecision(false));
        }

        Object backendResource = redisService.hGet(BACKEND_RESOURCE, request.getURI().getPath());
        Set<String> strings = Convert.toSet(String.class, backendResource);

        // 对应跨域的预检请求直接放行
        if (request.getMethod() == HttpMethod.OPTIONS) {
            return Mono.just(new AuthorizationDecision(true));
        }
        if (CollUtil.isEmpty(strings)) {
            return Mono.just(new AuthorizationDecision(true));
        }
        //认证通过且角色匹配的用户可访问当前路径
        return mono
                .filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                .any(strings::contains)
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));

    }
}
